package org.darkforest.ucenter.service.impl;

import org.apache.commons.collections.CollectionUtils;
import org.darkforest.dao.mapper.ProxyMapper;
import org.darkforest.enums.EmployeeLevel;
import org.darkforest.enums.MemberType;
import org.darkforest.model.Member;
import org.darkforest.model.MemberWithBLOBs;
import org.darkforest.model.Proxy;
import org.darkforest.ucenter.service.MemberLevelService;
import org.darkforest.ucenter.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * MemberLevelServiceImpl
 * Created by Justin on 15/5/24.
 */
@Service
public class MemberLevelServiceImpl implements MemberLevelService {

    @Autowired
    @Qualifier("memberServiceImpl")
    private MemberService memberService;

    @Autowired
    private ProxyMapper proxyMapper;


    @Override
    public void setEmployeeLevel(Integer memberId, Integer level) {
        MemberWithBLOBs member = new MemberWithBLOBs();
        member.setMemberId(memberId);
        member.setEmployeeLevel(level);
        memberService.updateMember(member);
    }

    @Override
    public void setMerchantLevel(final Integer memberId, Integer level) {
        Proxy proxy = findByMemberId(memberId);
        if (proxy == null) {
            return;
        }

        updateLevel(proxy.getProxyId(), level);
    }

    @Override
    public void raiseMerchantLevel(Integer memberId) {
        Proxy proxy = findByMemberId(memberId);
        if (proxy == null) {
            return;
        }
        updateLevel(proxy.getProxyId(), getNextLevel(proxy.getProxyLevel()));
    }

    @Override
    public List<Member> getEmployeesByLevel(EmployeeLevel level) {
        Member condition = new Member();
       // condition.setMemberType(MemberType.EMPLOYEE.ordinal());
        condition.setMemberTypeEnum(MemberType.EMPLOYEE);
        condition.setEmployeeLevel(level.ordinal());

        return memberService.findByCondition(condition);
    }

    private void updateLevel(Integer proxyId, Integer level) {
        Proxy proxy = new Proxy();
        proxy.setProxyId(proxyId);
        proxy.setProxyLevel(level);
        proxy.setLevelUpgradeTime(new Date());
        proxyMapper.updateByPrimaryKeySelective(proxy);
    }

    private Integer getNextLevel(Integer level) {
        if (level == null) {
            return 3;
        }
        Integer result = level - 1;
        if (result < 1) {
            return 1;
        }
        return result;
    }

    private Proxy findByMemberId(final Integer memberId) {
        List<Proxy> proxies = proxyMapper.findProxyByCondition(new Proxy() {
            {
                setMemberProxyRel(memberId);
            }
        });

        if (CollectionUtils.isEmpty(proxies)) {
            return null;
        }
        return proxies.get(0);
    }
}
